package com.sogou.ime.ui.filemgr;

import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.http.util.EncodingUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class VkTypeXML {
	public static final String CURR = "ActiveLayout";

    public static final String LAYOUT = "Layout";

    private String mPath = null;
    
    private String curr_layout = null;
    
    private List<String> layout = new ArrayList<String>();
    
    public VkTypeXML(String path) {
        mPath = path;
        parse();
    }     

	public String getCurr_layout() {
		return curr_layout;
	}

	public void setCurr_layout(String curr_layout) {
		this.curr_layout = curr_layout;
	}

	public List<String> getLayout() {
		return layout;
	}

	public void setLayout(List<String> layout) {
		this.layout = layout;
	}

	public String getmPath() {
		return mPath;
	}

	public void setmPath(String mPath) {
		this.mPath = mPath;
	}
	
	public static String readFile(String filePath) {
		String text = null;
		if (filePath != null) {
			try {
				FileInputStream fin = new FileInputStream(filePath);
				int length = fin.available();
				byte[] buffer = new byte[length];
				fin.read(buffer);
				text = EncodingUtils.getString(buffer, "UTF-8");
				fin.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return text;
	}
    
    public void parse() {
        if (mPath == null) {
            return;
        }

        String xmlBuf = readFile(mPath);

        if (xmlBuf == null) {
            return;
        }

        try {
            DocumentBuilderFactory docFactory = DocumentBuilderFactory
                    .newInstance();
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
            Document doc = docBuilder.parse(new ByteArrayInputStream(xmlBuf
                    .replaceAll("&", "&amp;").getBytes()));
            NodeList nodeList = doc.getDocumentElement().getChildNodes();            
            
            for (int i = 0; i < nodeList.getLength(); i++) {
                Node node = nodeList.item(i);

                if (node.getNodeName().equals(CURR)) {          
                	curr_layout = node.getTextContent();
                }else if (node.getNodeName().equals(LAYOUT)) {
                	layout.add(node.getTextContent());
				}
            }
        } catch (Exception e) {
            return;
        }
    }
}
